//
//  HomeControlFocusAdjustView.swift
//  WatermarkCamera
//
//  Created by Python on 2024/7/24.
//

import UIKit
import RxRelay

class HomeControlFocusAdjustView: BaseView {

    private lazy var stackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .horizontal
        stackV.spacing = 12.0
        stackV.distribution = .fill
        stackV.alignment = .center
        return stackV
    }()
    
    /// 焦距倍数选择view
    private(set) lazy var focusSelectView: HomeControlFocusSelectView = {
        let view = HomeControlFocusSelectView(width: 36.0, scaleModels: scaleModels)
        return view
    }()
    /// 刻度view
    private(set) lazy var ruleView: HomeControlRuleView = {
        let view = HomeControlRuleView(numOfUnits: 2, scalesOfUnit: 5)
        view.unitValues = scaleModels.map({ $0.times.rawValue })
        view.isHidden = true
        return view
    }()

    /// 焦距倍数数组
    private lazy var scaleModels: [FocusScale] = {
        let models = FocusScale.Times.allCases.map { times -> FocusScale  in
            let model = FocusScale()
            model.times = times
            model.scale = times.rawValue
            return model
        }
        return models
    }()

    
    private var workItem: DispatchWorkItem?
    
    let didSelectedFocusScale: PublishRelay<CGFloat> = .init()
    

    // MARK: UI
    override func createUI() {
        super.createUI()
        backgroundColor = UIColor.clear
        // stackView
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        // 选择焦距
        stackView.addArrangedSubview(focusSelectView)
        focusSelectView.snp.makeConstraints { make in
            make.width.equalTo(focusSelectView.viewWidth)
        }
        // 刻度
        let focusSelectViewH = focusSelectView.fittedHeight()
        let ruleH = focusSelectViewH - focusSelectView.itemWH
        stackView.addArrangedSubview(ruleView)
        ruleView.snp.makeConstraints { make in
            make.width.equalTo(20.0)
            make.height.equalTo(ruleH)
        }
        
    }
    
    // MARK: Bind Action
    
    override func bindForwardAction() {
        super.bindForwardAction()
        // 切换焦距倍数
        focusSelectView.didSelectedFocusScale.subscribe(onNext: {
            [weak self] scale in
            guard let self = self else { return }
            self.ruleView.value = scale
            self.didSelectedFocusScale.accept(scale)
            self.hideRuleView(delay: true)
        }).disposed(by: rx.disposeBag)
    }

}

extension HomeControlFocusAdjustView {
    
    /// 计算高度
    func fittedHeight() -> CGFloat {
        return focusSelectView.fittedHeight()
    }
    
    /// 显示刻度和缩放倍数
    func showRuleView() {
        self.workItem?.cancel()
        ruleView.isHidden = false
        // 重置当前选中的倍数的值
        focusSelectView.selectedScaleModel?.reset()
        // 显示所有焦距选项的倍数
        scaleModels.forEach {
            $0.isShowScale = true
        }
        // 刷新UI
        focusSelectView.reloadData()
    }
    
    /// 隐藏刻度和缩放倍数
    func hideRuleView(delay: Bool = false) {
        self.workItem?.cancel()
        let workItem = DispatchWorkItem {
            // 隐藏刻度
            self.ruleView.isHidden = true
            // 隐藏未选中的倍数
            self.scaleModels.forEach {
                $0.isShowScale = $0.isSelected
            }
            // 修改当前选中的焦距倍数值
            self.focusSelectView.selectedScaleModel?.scale = self.ruleView.value
            // 刷新
            self.focusSelectView.reloadData()
        }
        self.workItem = workItem
        let time = delay ? 2.0 : 0.0
        DispatchQueue.main.asyncAfter(deadline: .now() + time, execute: workItem)
    }
    
    
    /// 设置缩放倍数
    /// - Parameters:
    ///   - scale: 缩放倍数
    ///   - isShowScales: 是否显示所有缩放倍数
    func set(scale: CGFloat, isShowScales: Bool) {
        guard scaleModels.count >= 2,
              let minScale = scaleModels.first?.times.rawValue,
              let maxScale = scaleModels.last?.times.rawValue
        else { return }
        // 焦距倍数校准
        let _scale = min(max(scale, minScale), maxScale)
        focusSelectView.set(scale: _scale, isShowScales: isShowScales)
        ruleView.value = _scale
    }
}

